﻿Imports System.IO

Public Class Pedidos
    Dim Pedido As String = ""
    Dim dtProductos As DataTable
    Dim pCliente As String

    Dim maxVenta As Double = 0
    Dim TipoPedido As tPedido

    Dim cFiltros As Collection

    Dim vSubTotal As Double = 0
    Dim vIVA As Double = 0
    Dim vTotal As Double = 0

    Enum tPedido
        Contado = 1
        Credito
    End Enum

    Public Sub New()

        ' Llamada necesaria para el diseñador.
        InitializeComponent()

        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().

    End Sub

    Public Sub New(ByVal id As String, ByRef regreso As Boolean)

        ' Llamada necesaria para el diseñador.
        InitializeComponent()

        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().

        btnClientes.Visible = False

        regreso = Carga_Cliente(id)

    End Sub

    Private Sub Pedidos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not File.Exists(ruta_programa & "\Info.xml") Then
            msg.Mostrar("No se puede encontrar el archivo de Datos", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If

        Carga_Datos()

        dsInfo = New DataSet
        dsInfo.ReadXml(ruta_programa & "\Info.xml")
        'dsInfo.Tables("CLIENTES").Columns("SALDO").ExtendedProperties.Add("formato", "$ ###,###,##0.00")
        'dsInfo.Tables("CUENTAS").Columns("SALDO").ExtendedProperties.Add("formato", "$ ###,###,##0.00")
        'dsInfo.Tables("CUENTAS").Columns("IMPORTE").ExtendedProperties.Add("formato", "$ ###,###,##0.00")


    End Sub

    Private Sub Limpia()
        pCliente = ""
        gbCliente.Controls.Clear()
        Pedido = ""
        If Not dtProductos Is Nothing Then dtProductos.Rows.Clear()
        btnCancelar.Visible = False
        btnGuardar.Visible = False
        gbCliente.Visible = False
        pbImagen.Visible = False
        gbPedido.Visible = False
        dgDatos.Visible = False
        dgDatos.DataSource = Nothing
        pbImagen.Image = Nothing
    End Sub

    Private Sub Pedidos_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                btnClientes_Click(Nothing, Nothing)

            Case Keys.F2
                btnProductos_Click(Nothing, Nothing)

            Case Keys.F9
                If btnGuardar.Visible AndAlso btnGuardar.Enabled Then
                    btnGuardar_Click(Nothing, Nothing)
                End If
            Case Keys.F12
                If btnCancelar.Visible AndAlso btnCancelar.Enabled Then
                    btnCancelar_Click(Nothing, Nothing)
                End If
        End Select
    End Sub

    Private Sub btnClientes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClientes.Click
        Me.Cursor = Cursors.WaitCursor
        Dim forma As New Buscar()
        Dim columnas As New Collection
        Dim cols As String = "CCLIE,NOMBRE,RFC,DIR,COLONIA,POB,CODIGO,TELEFONO,EMAIL,CLASIFIC"
        For Each col As String In cols.Split(",")
            columnas.Add(col, col)
        Next

        Dim clie As String = ""

        Dim cClie As Collection = forma.Mostrar(Color.AliceBlue, False, dsInfo.Tables("CLIENTES"), columnas, True)

        If cClie.Count > 0 Then
            clie = CType(cClie(1), Buscar.Resultado).id
        End If

        Me.Cursor = Cursors.Default

        If clie.Trim.Length > 0 Then
           
            If Pedido.Trim.Length > 0 AndAlso msg.Mostrar("Ya hay un pedido cargado?" & vbCrLf & vbCrLf & "Deseas cancelar el pedido y crear uno nuevo con este cliente?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = "&No" Then
                Exit Sub
            End If

            Carga_Cliente(clie)
            
        End If

    End Sub

    Private Function Carga_Cliente(ByVal clie As String) As Boolean

        Dim regreso As Boolean = True


        Dim deudas As DataRow() = dsInfo.Tables("CUENTAS").Select("CCLIE='" & clie & "'")
        Dim fVencidas As String = "'A'"
        For Each fila As DataRow In deudas
            fVencidas += ",'" & fila("REFER") & "'"
        Next
        'If fVencidas.EndsWith(",") Then fVencidas = fVencidas.Substring(0, fVencidas.Length - 1)


        Dim saldo As Object = dsInfo.Tables("CUENTAS").Compute("SUM(SALDO)", "CCLIE='" & clie & "'")
        Dim pagos As Object = dsData.Tables("PAGOS").Compute("SUM(IMPORTE)", "CCLIE='" & clie & "' AND REFER IN (" & fVencidas & ")")
        Dim credito As Object = CType(dsInfo.Tables("CLIENTES").Select("CCLIE='" & clie & "'").GetValue(0), DataRow)("LIM_CRED")
        Dim vendido As Object = dsData.Tables("FACTURAS").Compute("SUM(TOTAL)", "CCLIE='" & clie & "' AND TIPO='C'")

        If saldo Is DBNull.Value Then saldo = 0
        If pagos Is DBNull.Value Then pagos = 0
        If credito Is DBNull.Value Then credito = 0
        If vendido Is DBNull.Value Then vendido = 0

        Dim saldo_real As Double = saldo - pagos - vendido

        Dim pag As New Pagos

        If credito = 0 Then
            If pag.Mostrar(clie) Then
                Crea_Pedido(clie, tPedido.Contado)
            Else
                Limpia()
                regreso = False
            End If
        ElseIf saldo_real > 0 Then
            Dim res As String = ""
            msg.clear()

            msg.AgregarBoton("Pagar")
            msg.AgregarBoton("Usar Crédito")
            If credito - vendido - saldo + pagos > 0 Then msg.AgregarBoton("Compra de Contado")
            msg.AgregarBoton("Cancelar")

            res = msg.Mostrar("Este cliente tiene un saldo de:" & vbCrLf & vbCrLf & Format(saldo_real, "$ ###,###,##0.00") & vbCrLf & vbCrLf & "Que desea hacer?", "", MessageBoxIcon.Question)

            Select Case res
                Case "Pagar"
                    If pag.Mostrar(clie) Then
                        If msg.Mostrar("Deseas continuar usando el crédito disponible?", "", MessageBoxButtons.YesNo) = "&Si" Then
                            Crea_Pedido(clie, tPedido.Credito)
                        Else
                            Limpia()
                            regreso = False
                        End If
                    Else
                        Limpia()
                        regreso = False
                    End If
                Case "Usar Crédito"
                    Crea_Pedido(clie, tPedido.Credito)
                Case "Compra de Contado"
                    Crea_Pedido(clie, tPedido.Contado)
                Case "Cancelar"
                    Limpia()
                    regreso = False
            End Select
        Else
            Dim res As String = ""
            msg.clear()

            msg.AgregarBoton("Usar Crédito")
            If credito - vendido - saldo + pagos > 0 Then msg.AgregarBoton("Compra de Contado")
            msg.AgregarBoton("Cancelar")

            res = msg.Mostrar("Que desea hacer?", "", MessageBoxIcon.Question)

            Select Case res
                Case "Usar Crédito"
                    Crea_Pedido(clie, tPedido.Credito)
                Case "Compra de Contado"
                    Crea_Pedido(clie, tPedido.Contado)
                Case "Cancelar"
                    Limpia()
                    regreso = False
            End Select
        End If

        Carga_Cliente = regreso
    End Function

    Private Sub btnProductos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProductos.Click
        Me.Cursor = Cursors.WaitCursor
        Dim forma As New Buscar()
        Dim columnas As New Collection
        Dim cols As String = "CLAVE,DESCR,EXIST,UNIDAD,LINEA"
        For Each col As String In cols.Split(",")
            columnas.Add(col, col)
        Next

        Dim sComp As New Buscar.Comparativa
        sComp.Costo = "COSTO_PROM"
        sComp.Precio = "PRECIO"
        sComp.Nombre = "UTILIDAD"
        sComp.Tipo_Iva = "CVEESQIMP"
        If (Not pCliente Is Nothing) AndAlso pCliente.ToString.Trim.Length > 0 Then
            sComp.Cliente = pCliente
        Else
            Dim valor As String = Valor_Config("FIJOS", "Cliente Mostrador", "MOSTR")
            If valor.Trim.Length = 0 Then
                sComp.Cliente = Nothing
            Else
                sComp.Cliente = valor
            End If
        End If


        Dim cProd As Collection = New Collection

        If Me.Pedido.Trim.Length > 0 Then
            cProd = forma.Mostrar(Color.Honeydew, True, dsInfo.Tables("PRODUCTOS"), columnas, False, sComp)

            For Each prod As Buscar.Resultado In cProd
                Carga_Producto(prod.id, prod.cantidad)
            Next
        Else
            forma.Mostrar(Color.Honeydew, True, dsInfo.Tables("PRODUCTOS"), columnas, True, sComp)
        End If



        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Carga_Producto(ByVal id_producto As String, ByVal cantidad As Double)
        If TipoPedido = tPedido.Credito Then
            Define_Filtros()
            Dim res As String = CType(dsInfo.Tables("PRODUCTOS").Select(dsInfo.Tables("PRODUCTOS").Columns(0).ColumnName & "='" & id_producto & "'").GetValue(0), DataRow)(1)
            For Each filtro As String In cFiltros
                If res.ToString.ToUpper.Contains(filtro.ToUpper) Then
                    msg.Mostrar("Este producto no puede ser agregado a una venta a crédito", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End If
            Next
        End If

        Dim cant As Double = cantidad

        If cant = 0 Then cant = Val(num.Mostrar(, True, "Escribe la cantidad"))

        If cant > 0 Then
            Dim existe As DataRow() = dtProductos.Select("Articulo='" & id_producto & "'")

            If existe.Length > 0 Then
                existe(0)(1) += cant
                existe(0)(6) = existe(0)(4) + existe(0)(5)
                existe(0)(7) = existe(0)(6) * existe(0)(1)
                selecciona(existe(0)(0))
            Else
                Dim res As DataRow = dsInfo.Tables("PRODUCTOS").Select(dsInfo.Tables("PRODUCTOS").Columns(0).ColumnName & "='" & id_producto & "'").GetValue(0)


                Dim bmp As New Bitmap(My.Resources._Error)
                Comprime_Imagen(bmp, 25, 25)

                Dim fila As DataRow = dtProductos.NewRow
                fila(0) = dtProductos.Rows.Count + 1
                fila(1) = cant
                fila(2) = id_producto
                fila(3) = res(1)
                Dim politicas As DataRow() = dsInfo.Tables("POLITICAS").Select("CLIE='" & pCliente & "' and CLV_INI<=" & id_producto & " and CLV_FIN>=" & id_producto)
                Dim precio As Integer = 1
                If politicas.Length > 0 Then
                    precio = Val(politicas(0)("LISTA_PREC"))
                End If

                fila(4) = res("PRECIO" & precio.ToString)
                Dim iva As Double = (CType(dsInfo.Tables("IMPUESTOS").Select("CVEESQIMPU='" & res("CVEESQIMP") & "'").GetValue(0), DataRow)("IMPUESTO4") / 100) * res("PRECIO" & precio.ToString)
                fila(5) = iva 'Truncar(iva, 2)
                fila(6) = fila(4) + fila(5)
                fila(7) = fila(6) * fila(1)
                fila(8) = New Bitmap(bmp)

                If maxVenta > 0 AndAlso maxVenta - vTotal - fila(7) < 0 Then
                    msg.Mostrar("Esta venta excede el crédito disponible", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    dgDatos.Focus()
                    Exit Sub
                End If

                dtProductos.Rows.Add(fila)
                selecciona(dtProductos.Rows.Count)
            End If
        End If


        calcular_pedido()
    End Sub

    Private Sub Define_Filtros()
        cFiltros = New Collection
        Dim filtros As String = Valor_Config("FIJOS", "Filtro Contado")
        For Each filtro As String In filtros.Split(",")
            filtro = filtro.Trim
            If Not cFiltros.Contains(filtro) Then
                cFiltros.Add(filtro, filtro)
            End If
        Next
    End Sub

    Private Sub selecciona(ByVal item As Integer)
        For Each fila As DataGridViewRow In dgDatos.Rows
            If fila.Cells(0).Value = item Then
                fila.Selected = True
                Exit Sub
            End If
        Next
    End Sub

    Public Function Truncar(ByVal value As Double, ByVal escala As Integer) As Double
        Truncar = Int(value * 10 ^ escala) / (10 ^ escala)
    End Function

    Private Sub calcular_pedido()
        vsubTotal = 0
        vIVA = 0
        vTotal = 0

        Dim util As Double = 0


        If Not dtProductos Is Nothing Then
            Dim item As Integer = 1
            For Each fila As DataRow In dtProductos.Rows
                Dim precio As Double = CType(dsInfo.Tables("PRODUCTOS").Select("CLAVE='" & fila(2) & "'").GetValue(0), DataRow)("PRECIO1")
                Dim costo As Double = CType(dsInfo.Tables("PRODUCTOS").Select("CLAVE='" & fila(2) & "'").GetValue(0), DataRow)("COSTO_PROM")
                util += ((precio - costo) * fila(1))
                fila(0) = item
                vSubTotal += fila(1) * fila(4)
                vIVA += fila(1) * fila(5)
                fila(7) = fila(1) * (fila(4) + fila(5))
                vTotal += fila(7)
                item += 1
            Next
        End If

        lbUtilidad.Text = Format(util, "$ ###,###,##0.00")

        dgDatos.Refresh()


        If dtProductos.Rows.Count > 0 Then btnGuardar.Enabled = True

        lbSubtotal.Text = Format(vsubTotal, "$ ###,###,##0.00")
        lbIVA.Text = Format(vIVA, "$ ###,###,##0.00")
        lbTotal.Text = Format(vTotal, "$ ###,###,##0.00")

        lbDisponible.Text = Format(maxVenta - vTotal, "$ ###,###,##0.00")

        dgDatos.Focus()
    End Sub

    Private Sub Crea_Pedido(ByVal id_cliente As String, ByVal PedTipo As tPedido)
        Limpia()

        If PedTipo = tPedido.Credito Then
            Dim deudas As DataRow() = dsInfo.Tables("CUENTAS").Select("CCLIE='" & id_cliente & "'")
            Dim fVencidas As String = "'A'"
            For Each filaa As DataRow In deudas
                fVencidas += ",'" & filaa("REFER") & "'"
            Next

            Dim saldo As Object = dsInfo.Tables("CUENTAS").Compute("SUM(SALDO)", "CCLIE='" & id_cliente & "'")
            Dim pagos As Object = dsData.Tables("PAGOS").Compute("SUM(IMPORTE)", "CCLIE='" & id_cliente & "' AND REFER IN (" & fVencidas & ")")
            Dim credito As Object = CType(dsInfo.Tables("CLIENTES").Select("CCLIE='" & id_cliente & "'").GetValue(0), DataRow)("LIM_CRED")
            Dim vendido As Object = dsData.Tables("FACTURAS").Compute("SUM(TOTAL)", "CCLIE='" & id_cliente & "' AND TIPO='C'")

            If saldo Is DBNull.Value Then saldo = 0
            If pagos Is DBNull.Value Then pagos = 0
            If credito Is DBNull.Value Then credito = 0
            If vendido Is DBNull.Value Then vendido = 0

            maxVenta = credito - vendido - saldo + pagos

            lbDisp.Visible = True
            lbDisponible.Visible = True
            lbTipo.Text = "CREDITO"
            lbDisponible.Text = Format(maxVenta, "$ ###,###,##0.00")
            TipoPedido = tPedido.Credito
        Else
            lbDisp.Visible = False
            lbDisponible.Visible = False
            lbTipo.Text = "CONTADO"
            maxVenta = 0
            TipoPedido = tPedido.Contado
        End If

        lbUtilidad.Text = Format(0, "$ ###,###,##0.00")

        Pedido = Valor_Config("EMPRESA", "Serie") & Val(Valor_Config("EMPRESA", "Pedido")).ToString
        pCliente = id_cliente

        gbPedido.Visible = True

        lbPedido.Text = Pedido
        lbFecha.Text = Format(Now, "dd/MM/yyyy")
        lbEntrega.Text = Format(DateAdd(DateInterval.Day, 2, Now), "dd/MM/yyyy")

        Dim fila As DataRow = dsInfo.Tables("CLIENTES").Select(dsInfo.Tables("CLIENTES").Columns(0).ColumnName & "='" & id_cliente & "'").GetValue(0)

        Dim y As Integer = 18
        For Each col As DataColumn In dsInfo.Tables("CLIENTES").Columns
            Dim lbTit As New Label
            lbTit.AutoSize = False
            lbTit.Size = New Size(gbCliente.Width / 3, 15)
            lbTit.TextAlign = ContentAlignment.MiddleLeft
            lbTit.Text = col.ColumnName & ":"
            lbTit.Font = New Font("Tahoma", 9, FontStyle.Bold)
            lbTit.BackColor = Color.Transparent
            lbTit.Location = New Point(0, y)

            Dim lbDat As New Label
            lbDat.AutoSize = False
            lbDat.Size = New Size((gbCliente.Width / 3) * 2, 15)
            lbDat.TextAlign = ContentAlignment.MiddleLeft
            If col.ExtendedProperties.Contains("formato") Then
                lbDat.Text = Format(fila(col.ColumnName), col.ExtendedProperties("formato"))
            Else
                lbDat.Text = fila(col.ColumnName)
            End If
            lbDat.Font = New Font("Tahoma", 9, FontStyle.Regular)
            lbDat.BackColor = Color.Transparent
            lbDat.Location = New Point((gbCliente.Width / 3), y)

            y += 15
            gbCliente.Controls.Add(lbTit)
            gbCliente.Controls.Add(lbDat)
        Next

        gbCliente.Height = y + 5

        gbCliente.Visible = True

        btnGuardar.Visible = True
        btnGuardar.Enabled = False
        btnCancelar.Visible = True
        'btnCancelar.Enabled = False
        btnCancelar.BringToFront()

        dtProductos = New DataTable
        dtProductos.Columns.Add("Item", GetType(Integer))
        dtProductos.Columns.Add("Cantidad", GetType(Double))
        dtProductos.Columns.Add("Articulo", GetType(String))
        dtProductos.Columns.Add("Descripcion", GetType(String))
        dtProductos.Columns.Add("Precio", GetType(Double))
        dtProductos.Columns.Add("IVA", GetType(Double))
        dtProductos.Columns.Add("Importe", GetType(Double))
        dtProductos.Columns.Add("Total", GetType(Double))
        dtProductos.Columns.Add("X", GetType(Image))

        dgDatos.DataSource = dtProductos

        For i As Integer = dgDatos.Columns.Count - 5 To dgDatos.Columns.Count - 1
            dgDatos.Columns(i).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        Next

        dgDatos.Columns(4).DefaultCellStyle.Format = "$ ###,###,##0.00"
        dgDatos.Columns(5).DefaultCellStyle.Format = "$ ###,###,##0.00"
        dgDatos.Columns(6).DefaultCellStyle.Format = "$ ###,###,##0.00"
        dgDatos.Columns(7).DefaultCellStyle.Format = "$ ###,###,##0.00"

        dgDatos.DefaultCellStyle.Font = New Font("Tahoma", 12, FontStyle.Regular)

        dgDatos.Visible = True
        pbImagen.Visible = True

        calcular_pedido()
    End Sub
    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        'If msg.Mostrar("Esta seguro que desea cancelar este pedido?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = "&Si" Then
        Limpia()
        Me.Close()
        'End If

    End Sub

    Private Sub dgDatos_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgDatos.CellContentClick
        If e.ColumnIndex = dgDatos.Columns.Count - 1 Then
            Elimina_Producto(e.RowIndex)
        End If
    End Sub

    Private Sub Elimina_Producto(ByVal indice As Integer)
        Dim item As Integer = dtProductos.Rows(indice)(0)
        For Each fila As DataRow In dtProductos.Select("Item=" & item)
            dtProductos.Rows.Remove(fila)
        Next
        calcular_pedido()
    End Sub

    Private Sub dgDatos_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgDatos.CellDoubleClick
        If dgDatos.SelectedRows.Count > 0 Then
            dgDatos.SelectedRows(0).Cells(1).Value = num.Mostrar(dgDatos.SelectedRows(0).Cells(1).Value, False, "Escribe la cantidad")
            calcular_pedido()
        End If
    End Sub

    Private Sub dgDatos_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgDatos.KeyDown
        If e.KeyCode = Keys.Delete Then
            If dgDatos.SelectedRows.Count > 0 Then
                Elimina_Producto(dgDatos.SelectedRows(0).Index)
            End If
        End If

        If e.KeyCode = Keys.Space Then
            dgDatos.SelectedRows(0).Cells(1).Value = num.Mostrar(dgDatos.SelectedRows(0).Cells(1).Value, False, "Escribe la cantidad")
            calcular_pedido()
        End If
    End Sub

    Private Sub dgDatos_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgDatos.SelectionChanged
        If dgDatos.SelectedRows.Count > 0 Then
            If Valida_Imagen(dgDatos.SelectedRows(0).Cells(2).Value) Then
                Dim bmp As New Bitmap(pbImagen.Width, pbImagen.Height)
                Dim g As Graphics = Graphics.FromImage(bmp)
                Dim alto As Integer = 25
                Dim sf As New StringFormat
                sf.Alignment = StringAlignment.Far
                g.DrawImage(Carga_Imagen(dgDatos.SelectedRows(0).Cells(2).Value), New Rectangle(0, 0, bmp.Width, bmp.Height))
                g.DrawString(dgDatos.SelectedRows(0).Cells(1).Value, New Font("Tahoma", alto, FontStyle.Bold), Brushes.Black, bmp.Width - 2, bmp.Height - alto - 15, sf)

                pbImagen.Image = New Bitmap(bmp)
            Else
                pbImagen.Image = Nothing
            End If
        End If
    End Sub

    Private Sub Pedidos_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Me.BringToFront()
    End Sub

    Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuardar.Click
        Dim cad As String = lbPedido.Text
        cad += vbCrLf & CType(dsInfo.Tables("CLIENTES").Select("CCLIE='" & pCliente & "'")(0), DataRow)("NOMBRE")
        cad += vbCrLf & Format(vTotal, "$###,###,##0.00")

        msg.clear()
        msg.AgregarBoton("Confirmar", My.Resources.edit)
        msg.AgregarBoton("Cancelar", My.Resources.busy)

        If msg.Mostrar("Confirma la siguiente información:" & vbCrLf & vbCrLf & cad, "", MessageBoxIcon.Information) = "Confirmar" Then
            Dim fila, fila_metas As DataRow
            '***Nueva fila para Facturas y ventas
            fila = dsData.Tables("FACTURAS").NewRow
            fila_metas = dsMetas.Tables("VENTAS").NewRow
            '************************************************
            fila("CCLIE") = pCliente
            fila_metas("CCLIE") = pCliente
            '************************************************
            '************************************************
            fila("FECHA") = lbFecha.Text
            fila_metas("FECHA") = lbFecha.Text
            '************************************************
            fila("ENTREGA") = lbEntrega.Text
            '************************************************
            fila("REFER") = lbPedido.Text
            fila_metas("PEDIDO") = lbPedido.Text
            '************************************************
            fila("USUARIO") = Valor_Config("EMPRESA", "ID Empleado en SAE")
            fila("SUBTOTAL") = vSubTotal
            fila("IVA") = vIVA
            '************************************************
            fila("TOTAL") = vTotal
            fila_metas("MONTO") = vTotal
            '************************************************
            If TipoPedido = tPedido.Contado Then
                fila("TIPO") = "X"
            Else
                fila("TIPO") = "C"
            End If
            fila("STATUS") = True
            '************************************************
            dsData.Tables("FACTURAS").Rows.Add(fila)
            dsMetas.Tables("VENTAS").Rows.Add(fila_metas)
            '************************************************

            For Each fProd As DataRow In dtProductos.Rows
                fila = dsData.Tables("PRODUCTOS").NewRow
                fila("REFER") = lbPedido.Text
                fila("ITEM") = fProd(0)
                fila("CANTIDAD") = fProd(1)
                fila("ARTICULO") = fProd(2)
                fila("DESCRIPCION") = fProd(3)
                fila("LINEA") = CType(dsInfo.Tables("PRODUCTOS").Select("CLAVE='" & fProd(2) & "'").GetValue(0), DataRow)("LINEA")
                fila("PRECIO") = fProd(4)
                fila("IVA") = fProd(5)
                fila("IMPORTE") = fProd(6)
                fila("TOTAL") = fProd(7)
                fila("STATUS") = True
                dsData.Tables("PRODUCTOS").Rows.Add(fila)
            Next

            'If TipoPedido = tPedido.Contado Then
            '    msg.Mostrar("Debes de cobrar:" & vbCrLf & vbCrLf & Format(vTotal, "$ ###,###,##0.00"), "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            '    Dim fPag As DataRow = dsData.Tables("PAGOS").NewRow
            '    fPag("CCLIE") = pCliente
            '    fPag("REFER") = lbPedido.Text
            '    fPag("IMPORTE") = vTotal
            '    fPag("FECHA") = Format(Now, "dd/MM/yyyy")
            '    fPag("USUARIO") = Valor_Config("EMPRESA", "ID del Vendedor")
            '    fPag("TIPO") = "X"
            '    dsData.Tables("PAGOS").Rows.Add(fPag)
            'End If

            Dim pedido As Integer = Val(Valor_Config("EMPRESA", "Pedido")) + 1

            CType(dsConfig.Tables("EMPRESA").Select("Concepto='Pedido'").GetValue(0), DataRow)(1) = pedido

            Guarda_Datos()

            Limpia()

            Imprime_Pedido(lbPedido.Text)

            msg.Mostrar("Se ha guardado la factura con éxito", "", MessageBoxButtons.OK, MessageBoxIcon.Information)

            Me.Close()

        End If

    End Sub

    Private Sub btnGuardar_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles btnGuardar.KeyPress

    End Sub

    Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click

    End Sub
End Class